package RpcServer.impl;

import RequestHandle.RequestHandler;
import RequestHandle.RequestHandlerThread;
import RpcServer.RpcServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import registerCenter.ServiceRegistry;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class RpcServerBIO implements RpcServer {
    public static int corePoolSize = 5;
    public static int maximumPoolSize = 50;
    public static long keepAliveTime = 60;
    public final ExecutorService threadPool;
    private final ServiceRegistry serviceRegistry;

    private RequestHandler requestHandler;

    public RpcServerBIO(ServiceRegistry serviceRegistry){
        this.serviceRegistry = serviceRegistry;
        this.requestHandler = new RequestHandler();

        BlockingQueue<Runnable> workingQueue = new ArrayBlockingQueue<>(100);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();

        threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS,workingQueue, threadFactory);
    }

    @Override
    public void start(int port){
        try(ServerSocket socket = new ServerSocket(port)){
            Socket cli;

            while ((cli = socket.accept()) != null){
                System.out.println("客户端已连接，ip:port is ---->  "+cli.getInetAddress()+":"+cli.getPort());
                threadPool.execute(new RequestHandlerThread(cli, serviceRegistry, requestHandler));
            }
        }catch (Exception e){
            System.out.println("服务端启动失败！");
        }
    }
}
